//
//  PlayerManagedObject.m
//  prototype
//
//  Created by OS X on 11-12-18.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "PlayerManagedObject.h"
#import "GameManagedObject.h"


@implementation PlayerManagedObject

+ (PlayerManagedObject *)playerWithResult:(NSDictionary *)result inManagedContext:(NSManagedObjectContext *)context
{
    // Check if the entity already exists
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    request.entity = [NSEntityDescription entityForName:@"Player" inManagedObjectContext:context];
    request.predicate = [NSPredicate predicateWithFormat:@"name = %@ AND ai = %@", 
                         [result objectForKey:@"name"], [result objectForKey:@"ai"]];
    NSError *error;
    PlayerManagedObject *player = nil;
    player = [[context executeFetchRequest:request error:&error] lastObject];
    NSNumberFormatter *n = [[NSNumberFormatter alloc] init];
    
    // The player does not exist
    if (!error && !player) {
        player = [NSEntityDescription insertNewObjectForEntityForName:@"Player" inManagedObjectContext:context];
        player.name = [result objectForKey:@"name"];
        player.ai = [result objectForKey:@"ai"];
    }
    // Set the Win, Loss, Draw
    BOOL draw = [n numberFromString:[result objectForKey:@"draw"]].boolValue;
    BOOL win = [n numberFromString:[result objectForKey:@"winner"]].boolValue;
    if (draw)
    {
        player.draws = [NSNumber numberWithInteger:player.draws.intValue+1];
    }
    else if (win)
    {
        player.wins = [NSNumber numberWithInteger:player.wins.intValue+1];
    }
    else
    {
        player.losses = [NSNumber numberWithInteger:player.losses.intValue+1];
    }
    
    return player;
}

@dynamic face;
@dynamic name;
@dynamic ai;
@dynamic wins;
@dynamic draws;
@dynamic losses;
@dynamic played;

@end
